<?php
// +----------------------------------------------------------------------
// | Description: 首页统计
// +----------------------------------------------------------------------
// | Author: yhq <934797303@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use app\admin\lib\enum\ApplyStatus;
use app\v2\model\ApplyOrder;
use think\Db;
use app\admin\model\Common;
use PHPExcel;
use app\admin\model\User;
use app\admin\model\Appuser;
class Index extends Common
{
    /**
     * 主要对apply表进行统计
     */
    protected $name = 'apply';
    protected $createTime = 'time';
    protected $updateTime = false;
    protected $autoWriteTimestamp = DATETIME;

    /**
     * 首页数据
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-31T11:26:22+0800
     * @param    [type]     $date  日期
     * @return   [type]                        [description]
     */
    public function getDataList($date = '',$dateEnd = '')
    {
        $isdate = $date;
        if ($date && $date != '') {
            $start_time = date('Y-m-d', strtotime($date));
            $end_time = date('Y-m-d',strtotime( $dateEnd));
        } else {
            $start_time = date('Y-m-d', time()) . ' 00:00:00';
            $end_time = date('Y-m-d', time()) . ' 23:59:59';
        }

        $date = array('BETWEEN', [$start_time, $end_time]);  //时间段

        // 是否指定日期
        if(strtotime($isdate))
        {

            $list1 = $this->data_query($date);  //某日指标
        }
        else
        {
            $list1 = $this->data_query();  //累计指标
        }

        $list2 = $this->data_query($date);  //某日指标
        $data = array(
            'all' => $list1,
            'today' => $list2
        );
        return resultArray(['data' => $data]);
    }


    /**
     * 查询数据
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-18T16:56:44+0800
     * @param    array $date 时间段
     * @return   [type]         [description]
     */
    public function data_query($date = '')
    {
        if ($date !== '') {
         
            $where_yanqi['pay_time']                                   = $date;          // 延期时间
            $where_user_new['create_time']                             = $date;          // 新用户注册时间
            $where_user['create_time']                                 = $date;          // 用户注册时间
            $where_apply['time']                                       = $date;          // 申请金额
            $where_fk['fk_time']                                       = $date;          // 放款金额
            $where_yuqi['appoint_time']                                = $date;          // 逾期总额
            $where_hk['pay_time']                                       = $date;           // 放款总额
            $where_refuse['time|check_time|check2_time|lendmoneydate'] = $date;          // 拒绝
            $where_time['time']                                        = $date;          // 统计续贷率

            $where_auth['create_time']                                        = $date;          // 统计续贷率
            // $where1['reg_time']      = $date;
            // $whereinfo['create_time']      = $date;
            // $where2['time']          = $date;
            // $where3['time']          = $date;
            // $where4['fk_time']       = $date;
            // $where5['fk_time']       = $date;
            // $where6['hk_time']       = $date;
            // $where7['hk_time']       = $date;
            // $where8['lendmoneydate'] = $date;
            // $where9['lendmoneydate'] = $date;
            // $where10['appoint_time'] = $date;
            // $where11['appoint_time'] = $date;
            
        }


        # 延期费用和次数计算
        $where_yanqi['result_pay'] = 'SUCCESS';
        $where_yanqi['type'] = ['in', '2'];


        $data_yanqi_money = $this->yanqi_count($where_yanqi, 'money');
        $data_yanqi_number = $this->yanqi_count($where_yanqi, 'number');


        # 填写资料的用户
//        $where_is = 'operator_outUniqueId is not null';
//        if(!empty($UserInfo['company']) && !empty($UserInfo['address']) && !empty($UserInfo['zhima']) && !empty($UserInfo['qq']) && !empty($UserInfo['mon_income']) && !empty($UserInfo['wechat_id']) && !empty($UserInfo['payday']) && !empty($UserInfo['zmf']) && !empty($UserInfo['negative_img']) && !empty($UserInfo['job'])){
//            $data['base'] = '1';
//        }
        //基础信息 身份证 运营商 银行卡
//        $UserInfo['company&address&zhima&qq&mon_income&wechat_id&payday&zmf&negative_img&job'] = ['neq',''];
//        $UserInfo['id_card_img1&id_card_img2&id_card_img3'] = ['neq',''];
        // $UserInfo['operator_outUniqueId'] = ['exp', 'is not null'];
//        $UserInfo['bank_card_number'] = ['neq',''];
        $UserInfo['directories'] = ['eq','1'];

        $data_user_new = $this->new_count($where_user_new, $UserInfo);
        $data_user_new = $data_user_new['count'];

        # 写的吐血的续贷率
        $xudai_count = $this->xudailv($where_time);
        // p($xudai_count);exit;
        # 注册用户
        $data_user = $this->new_count($where_user);
        
        $data_count_pingtai = $data_user['count_pingtai'];
        $data_count_tuiguan_count = $data_user['count_tuiguan_count'];
        $data_user = $data_user['count'];
        # 申请总额(金额)
        $data_apply_money = $this->status_count($where_apply, 'money');

        # 申请总额（数量）
        $data_apply_number = $this->status_count($where_apply, 'number');

        # 今日申请总额(金额)
        $where_apply['b.create_time'] = $date;
        $today_apply_money = $this->apply_count($where_apply, 'money');
        $today_apply_number = $this->apply_count($where_apply, 'number');

        # 过往申请
        $pass_apply_money = $data_apply_money - $today_apply_money;
        $pass_apply_number = $data_apply_number - $today_apply_number;

        # 放款金额/数量
        $where_fk['a.status'] = array('in', '3,4,5,12');
        $data_fk_money = $this->fk_count($where_fk, 'money');
        $data_fk_number = $this->fk_count($where_fk, 'number');


        # 逾期总额
        $where_yuqi['status'] = 4;
        if(is_array($where_yuqi['appoint_time'])){
            $where_yuqi['appoint_time'][1][0] = date('Y-m-d H:i:s', strtotime("{$where_yuqi['appoint_time'][1][0]} -1day"));
            $where_yuqi['appoint_time'][1][1] = date('Y-m-d H:i:s', strtotime("{$where_yuqi['appoint_time'][1][1]} -1day"));
        }

        $data_yuqi_money = $this->status_count($where_yuqi, 'money');
        $data_yuqi_number = $this->status_count($where_yuqi, 'number');


        # 拒绝
        if ($date) {
            $vtime = "BETWEEN '{$date[1][0]}' and '{$date[1][1]}'";
            $total = $this->all_refuseDate_count('total', $vtime);
            $data_refuse_money = $total['money'];
            $data_refuse_number = $total['number'];
        } else {
            $where_refuse['status'] = array('in', '6,7,8,10,11');
            $data_refuse_money = $this->status_count($where_refuse, 'money');
            $data_refuse_number = $this->status_count($where_refuse, 'number');
        }


        # 还款总额
        $where_hk['result_pay'] = 'SUCCESS';
        $where_hk['type'] = ['in','1,3'];
        $data_hk_money = $this->hk_count($where_hk, 'money');
        $data_hk_number = $this->hk_count($where_hk, 'number');

        #认证收费统计
        $where_auth['pay_result'] = 'SUCCESS';
        $data_auth_money = $this->auth_count($where_auth,'money');
        $data_auth_number = $this->auth_count($where_auth,'number');


        $list = array(
            //    'user_number' => $data1 ? $data1 : 0,
            // 'user_numberinfo' => $datainfo ? $datainfo : 0,
            'yanqi' => array(
                'money' => $data_yanqi_money ? $data_yanqi_money : 0,
                'number' => $data_yanqi_number ? $data_yanqi_number : 0
            ),
            'user_new' => array(
                'number' => $data_user ? $data_user : 0,
                'pingtai' => $data_count_pingtai ? $data_count_pingtai : 0,
                'tuiguang' => $data_count_tuiguan_count ? $data_count_tuiguan_count : 0
            ),
            'user' => array(
                'number' => $data_user_new ? $data_user_new : 0
            ),
            'xudai' => array(
                'number' => $xudai_count ? $xudai_count : 0
            ),
            'apply' => array(
                'money' => $data_apply_money ? $data_apply_money : 0,
                'number' => $data_apply_number ? $data_apply_number : 0,

                'now_money'=>$today_apply_money?$today_apply_money:0,
                'now_number' =>$today_apply_number?$today_apply_number:0,

                'pass_money'=>$pass_apply_money?$pass_apply_money:0,
                'pass_number' =>$pass_apply_number?$pass_apply_number:0,

            ),
            'fk' => array(
                'money' => $data_fk_money ? $data_fk_money : 0,
                'number' => $data_fk_number ? $data_fk_number : 0
            ),
            'yuqi' => array(
                'money' => $data_yuqi_money ? $data_yuqi_money : 0,
                'number' => $data_yuqi_number ? $data_yuqi_number : 0
            ),
            'refuse' => array(
                'money' => $data_refuse_money ? $data_refuse_money : 0,
                'number' => $data_refuse_number ? $data_refuse_number : 0
            ),
            'hk' => array(
                'money' => $data_hk_money ? $data_hk_money : 0,
                'number' => $data_hk_number ? $data_hk_number : 0
            ),

            'auth' => [
                'money' => $data_auth_money ? $data_auth_money : 0,
                'number' => $data_auth_number ? $data_auth_number : 0
            ]


            // 'loan' => array(
            // 	'number' => $data4 ? $data4 : 0,
            // 	'money'  => $data5 ? $data5 : 0
            // ),
            // 'repayment' => array(
            // 	'number' => $data6 ? $data6 : 0,
            // 	'money'  => $data7 ? $data7 : 0
            // ),
            // 'reject' => array(
            // 	'number' => $data8 ? $data8 : 0,
            // 	'money'  => $data9 ? $data9 : 0
            // 	),
            // 'overdue' => array(
            // 	'number' => $data10 ? $data10 : 0,
            // 	'money'  => $data11 ? $data11 : 0
            // ),
        );

        return $list;
    }

   public function xudailv($where_time = [])
   {
     

     if($where_time){

          $data_uid = Db::name('apply')->field('id,uid')->where($where_time)
                                                        ->group('uid')
                                                        ->order('id asc')
                                                        ->select();
       
    
     }elseif (!$where_time) {
          $data_uid = Db::name('apply')->field('id,uid')->where('status = 5')
                                                   ->where($where_time)
                                                   ->group('uid')
                                                   ->order('id asc')
                                                   ->select();
        
     }
     

     if(!$data_uid)
     {
        return $count=0;
     }
     $uids = [];
     foreach($data_uid as $value)
     {
        $uids[] = $value['uid'];
     }
     $map['uid'] = array('in',$uids);
     $count = 0 ;
     $data_id = Db::name('apply')->field('id,uid,status')->where($map)->select();


     # 无时间传入

     if(!$where_time)
     {
        foreach($data_uid as $value1)
        {
            foreach ($data_id as $key => $value2) {

               if($value1['uid'] == $value2['uid'])
               {
                    
                    if($value1['id'] < $value2['id'])
                    {
                        $count++;
                    }  

               } 
                
            }
        }
     }

    
    # 有时间传入 

     if($where_time)
     {
        foreach($data_uid as $value1)
        {
            foreach ($data_id as $key => $value2) {

               if($value1['uid'] == $value2['uid'])
               {
                    
                    if($value1['id'] > $value2['id'])
                    {
                    
                        if($value2['status'] == 5)
                        {
                            $count++;

                        }
                        
                    }  

               } 
                
            }
        }
     }
    

     return $count;
   }


    /**
     * 返回还款总额列表
     * @author cxr <1481746137@qq.com>
     * @param $date
     * @param int $status
     * @param line 线上 线下
     */
    public function getBackList($keywords, $page, $limit, $valuedate, $os = '', $status = "", $startdate, $enddate, $line, $isExport = false)
    {

        $map = [];
        $map['result_pay'] = 'SUCCESS';
        $map['type'] = ['in','1,3'];

        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate"));
            $map['pay_time'] = ['like', '%' . $valuedate . '%'];

        }
        if ($startdate != '') {
            $map['pay_time'] = array('BETWEEN', [$startdate, $enddate]);
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }

        if ($line == "online") {
            $map['pay_type'] = 'D';
        } elseif ($line == "offline") {
            $map['pay_type'] = 'XX';
        }


        $this->where($map);


        // 若有分页
        if ($page && $limit && !$isExport && !($keywords || $valuedate || $startdate)) {
            $this->page($page, $limit);
        }
        $this->field("b.*,a.name,a.status,a.money,a.uid,a.order_number,a.time,a.period,a.hk_time,mobile_type")
            ->alias("a")
            ->join("qh_user_order b", "a.order_number=b.apply_id", "RIGHT")
            ->order(array('status = 9' => 'desc', 'status = 3' => 'desc', 'status = 4' => 'desc', 'status = 5' => 'desc', 'status = 11' => 'desc', 'appoint_time' => 'desc', 'fives_claim_date' => 'desc', 'id' => 'asc'));

        if ($isExport == true && ($keywords || $valuedate || $startdate)) {
            $list = $this->select();
        } else {
            $listArray = $this->paginate();
            $list = $listArray->items();
            $data['dataCount'] = $listArray->total();
        }


        foreach ($list as $key => $value) {

            //第几次申请
            $mapuid['uid'] = $value['uid'];
            $count = $this->where($mapuid)->where('id', '<=', $value['id'])->count();
            $list[$key]['counts'] = $count;
            $list[$key]['actual_money'] = $list[$key]['money_order'];
            $list[$key]['times'] = substr($value['time'], 0, 10);
            $list[$key]['operator'] = $list[$key]['pay_type'] == 'XX' ? $this->getNameById($value['delay_aid']) : $list[$key]['name'];  //操作人员




            //导出时
            $isExport && $list[$key]['status_export'] = $this->statusInfo($list[$key]['status']);
            $isExport && $list[$key]['pay_type_export'] = $this->getPayType($list[$key]['pay_type']);
        }
        $data['list'] = $list;


//        //总数线上线下待优化
        // $where_hk['hk_time'] =  $date;// 日期
        $where_hk = $map;
//        $where_hk['status'] = 5;


        $total = $this->all_hk_count($where_hk);
        $data['money'] = $total['money'];
        $data['number'] = $total['number'];

        $online = $this->all_hk_count($where_hk, '', 'online');
        $data['onlineMoney'] = $online['money'];
        $data['onlineNumber'] = $online['number'];

        $data['offlineMoney'] = $data['money'] - $data['onlineMoney'];
        $data['offlineNumber'] = $data['number'] - $data['onlineNumber'];

        $offline = $this->all_hk_count($where_hk, '', 'offline');
        $data['offlineMoney'] = $offline['money'];
        $data['offlineNumber'] = $offline['number'];


        return $data;

    }

    /**
     * 返回还款总额列表
     * @author cxr <1481746137@qq.com>
     * @param $date
     * @param int $status
     * @param line 线上 线下
     */
    public function getBackList_old($keywords, $page, $limit, $valuedate, $os = '', $status = "", $startdate, $enddate, $line, $isExport = false)
    {

        $map = [];
        $map['type'] = ['in', '1'];
        $map['result_pay'] = 'SUCCESS'; // 订单完成并且支付完成

        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate"));
            $map['hk_time'] = ['like', '%' . $valuedate . '%'];
        }
        if ($startdate != '') {
            $map['hk_time'] = array('BETWEEN', [$startdate, $enddate]);
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }

        //线上线下
        $line == "online"  && $map['pay_type'] = ['in','D,DK'];
        $line == "offline" && $map['pay_type'] = 'XX' ;

        if ($status) {
            $map['status'] = $status;
        } else {
            $map['status'] = 5;
        }

        $this->where($map);


        // 若有分页
        if ($page && $limit && !$isExport && !($keywords || $valuedate || $startdate)) {
            $this->page($page, $limit);
        }
        $this
            // ->field('id,status,time,money,period,order_number,check_time,check_aid,check2_aid,check2_time,name,credit_rate,service_rate,procedure_rate,appoint_time,uid,treasurer,monepassdate,merchandiser,phone,hang,id_card')
            ->field("a.*,pay_type,pay_type as type,money_order")// group_concat(pay_type) 若是线下可能会包含线上，合并后可排除
            ->alias("a")
            ->join("qh_user_order b", "a.order_number=b.apply_id", "LEFT")
//            ->group("order_number")
            ->order(array('status = 9' => 'desc', 'status = 3' => 'desc', 'status = 4' => 'desc', 'status = 5' => 'desc', 'status = 11' => 'desc', 'appoint_time' => 'asc', 'fives_claim_date' => 'desc', 'id' => 'asc'));



        if ($isExport == true && ($keywords || $valuedate || $startdate)) {
            $list = $this->select();
        } else {
            $listArray = $this->paginate();
//            $line == "online"  && var_dump($this->getLastSql()); exit;
            $list = $listArray->items();
            $data['dataCount'] = $listArray->total();
        }


        foreach ($list as $key => $value) {

            //第几次申请
            $mapuid['uid'] = $value['uid'];
            $count = $this->where($mapuid)->where('id', '<=', $value['id'])->count();
            $list[$key]['counts'] = $count;

            //线下或线上还款
//            $list[$key]['actual_money'] =  $value['actual_money'];

            $where['apply_id'] = $value['order_number'];
            //$list[$key]['pay_type']  =  Db::name('user_order')->where($where)->value('pay_type');

            $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);
            $list[$key]['appoint_time'] = substr($value['appoint_time'], 0, 10);
            $list[$key]['times'] = substr($value['time'], 0, 10);
            $list[$key]['pay_type'] = $list[$key]['type'] == 'DK' ? 'D' : $list[$key]['type'];


            $mapseq['apply_id'] = $value['id'];
            $mapseq['auth_admin'] = 3;
            $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
            if (!$dataseq) {
                $list[$key]['seq'] = '';
            } else {
                $list[$key]['seq'] = $dataseq['seq'];
            }


            //导出时
            $isExport && $list[$key]['status_export'] = $this->statusInfo($list[$key]['status']);
            $isExport && $list[$key]['pay_type_export'] = $this->getPayType($list[$key]['pay_type']);
        }
        $data['list'] = $list;


        //总数线上线下待优化
        // $where_hk['hk_time'] =  $date;// 日期
        $where_hk = $map;
        $where_hk['status'] = 5;


        $total = $this->all_hk_count($where_hk);
        $data['money'] = $total['money'];
        $data['number'] = $total['number'];

        $online = $this->all_hk_count($where_hk, '', 'online');
        $data['onlineMoney'] = $online['money'];
        $data['onlineNumber'] = $online['number'];

        $data['offlineMoney'] = $data['money'] - $data['onlineMoney'];
        $data['offlineNumber'] = $data['number'] - $data['onlineNumber'];

//        $offline = $this->all_hk_count($where_hk, '', 'offline');
//        $data['offlineMoney'] = $offline['money'];
//        $data['offlineNumber'] = $offline['number'];


        return $data;

    }

    public function getOverdueList($keywords, $page, $limit, $valuedate, $os = '', $status = "", $startdate, $enddate, $line, $isExport = false)
    {


        $where_yuqi['status'] = 4;
        $map = $where_yuqi;

        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate -1day"));
            $map['appoint_time'] = ['like', '%' . $valuedate . '%'];
        }
//        var_dump($map['appoint_time']);exit;
        if ($startdate != '') {
            $map['appoint_time'] = array('BETWEEN', [$startdate, $enddate]);
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }

        $map1=$map;
        $this->where($map);

        // 若有分页
        if ($page && $limit && !$isExport && !($keywords || $valuedate || $startdate)) {
            $this->page($page, $limit);
        }
        $this->field("*")
            ->alias("a")
            ->order(array('a.status = 9' => 'desc', 'a.status = 3' => 'desc', 'a.status = 4' => 'desc', 'a.status = 5' => 'desc', 'a.status = 11' => 'desc', 'appoint_time' => 'asc', 'fives_claim_date' => 'desc', 'id' => 'asc'));

        if ($isExport == true && ($keywords || $valuedate || $startdate)) {
            $list = $this->select();
        } else {
            $listArray = $this->paginate();
            $list = $listArray->items();
            $data['dataCount'] = $listArray->total();
        }

        $list = modelo2array($list);

        foreach ($list as $key => $value) {


            //第几次申请
            $mapuid['uid'] = $value['uid'];
            $count = $this->where($mapuid)->where('id', '<=', $value['id'])->count();
            $list[$key]['counts'] = $count;


            $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);
            $list[$key]['appoint_time'] = substr($value['appoint_time'], 0, 10);
            $list[$key]['times'] = substr($value['time'], 0, 10);

            //应还金额
            $list[$key]['repay'] = $this->getRepay($list[$key]['status'], $value, $value['overdue_money']);


            $mapseq['apply_id'] = $value['id'];
            $mapseq['auth_admin'] = 3;
            $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
            if (!$dataseq) {
                $list[$key]['seq'] = '';
            } else {
                $list[$key]['seq'] = $dataseq['seq'];
            }

            //导出时
            $isExport && $list[$key]['status_export'] = $this->statusInfo($list[$key]['status']);

        }
        $data['list'] = $list;


        $where_yq = $map;

        $data_yuqi_money = $this->status_count($where_yq, 'money');
        $data_yuqi_number = $this->status_count($where_yq, 'number');

        $data['money'] = $data_yuqi_money;
        $data['number'] = $data_yuqi_number;
        $yqyh = $this->yqyh_sum($map1);
        $data['yqyh']=$yqyh;
        return $data;

    }





    public function yqyh_sum($where=null)
    {
        $yqyh = 0;
        $data = $this->where($where)->select();
        foreach ($data as $key=>$value){
            $yqyh+=$this->getRepay($data[$key]['status'], $value, $value['overdue_money']);
        }
        return $yqyh;
    }














    public function getRefuseList_bak($keywords, $page, $limit, $valuedate, $os = '', $status = "", $startdate, $enddate, $line, $isExport = false)
    {

        $where_refuse['a.status'] = array('in', '6,7,8,10,11');
//        $where_refuse['b.status'] = 0;
        $map = $where_refuse;

        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate"));
            $map['time|check_time|check2_time|lendmoneydate'] = ['like', '%' . $valuedate . '%'];
        }
        if ($startdate != '') {

            $refuse_time = '';
            $map[$refuse_time] = array('BETWEEN', [$startdate, $enddate]);
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }

        //人工 系统
        $type = "and status in(6,7,8,10,11)";
        if ($line == "online") {
            $map['status'] = array('in', '6,7,10,11');
            $type = "and status in(6,7,10,11)"; //用于日期筛选
        }
        if ($line == "online") {
            $map['status'] = array('in', '8'); //用于日期筛选
            $type = "and status in(8)";
        }


        $this->where($map);

        // 若有分页
        if ($page && $limit && !$isExport && !($keywords || $valuedate || $startdate)) {
            $this->page($page, $limit);
        }
        $this->field("a.*")
            ->alias("a")
            ->order(array('a.status = 9' => 'desc', 'a.status = 3' => 'desc', 'a.status = 4' => 'desc', 'a.status = 5' => 'desc', 'a.status = 11' => 'desc', 'appoint_time' => 'asc', 'fives_claim_date' => 'desc', 'a.id' => 'asc'));

        if ($isExport == true && ($keywords || $valuedate || $startdate)) {
            $list = $this->select();
        } else {
            $listArray = $this->paginate();
            $list = $listArray->items();
            $data['dataCount'] = $listArray->total();
        }

        foreach ($list as $key => $value) {

            $list[$key]['refuse_time'] = $this->getRefuseTimeByStatus($value);
            $list[$key]['refuse_person'] = $this->getRefuseByStatus($value);      //驳回操作人

            //第几次申请
            $mapuid['uid'] = $value['uid'];
            $count = $this->where($mapuid)->where('id', '<=', $value['id'])->count();
            $list[$key]['counts'] = $count;

            //线下或线上放款
            $where['apply_id'] = $value['order_number'];
            $list[$key]['pay_type'] = $value['status'];

            $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);
            $list[$key]['appoint_time'] = substr($value['appoint_time'], 0, 10);
            $list[$key]['times'] = substr($value['time'], 0, 10);

            $mapseq['apply_id'] = $value['id'];
            $mapseq['auth_admin'] = 3;
            $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
            if (!$dataseq) {
                $list[$key]['seq'] = '';
            } else {
                $list[$key]['seq'] = $dataseq['seq'];
            }

            //导出时
            $isExport && $list[$key]['status_export'] = $this->statusInfo($list[$key]['status']);
            $isExport && $list[$key]['pay_type_export'] = $value['status'] == "8" ? "系统拒绝" : "人工拒绝";
        }
        $data['list'] = $list;


        $where_refuse = $map;


        $total = $this->all_refuse_count($where_refuse, 'total');
        $data['money'] = $total['money'];
        $data['number'] = $total['number'];

        $online = $this->all_refuse_count($where_refuse, 'online');
        $data['onlineMoney'] = $online['money'];
        $data['onlineNumber'] = $online['number'];

        $offline = $this->all_refuse_count($where_refuse, 'offline');
        $data['offlineMoney'] = $offline['money'];
        $data['offlineNumber'] = $offline['number'];

        return $data;

    }

    /**
     * 排序
     * @author cxr <1481746137@qq.com>
     * @return \think\model\relation\HasOne
     */
    public function claimSeq(){
        return $this->hasOne("ClaimSeq","apply_id","id")->field("seq,apply_id")->where("auth_admin",3);
    }

    /**
     * 操作人
     * @author cxr <1481746137@qq.com>
     * @return $this
     */
    public function checkAid(){
        return $this->hasOne("User",'id',"check_aid")->field("id,username");
    }

    public function check2Aid(){
        return $this->hasOne("User",'id',"check2_aid")->field("id,username");
    }

    public function merchandiser(){
        return $this->hasOne("User",'id',"merchandiser")->field("id,username");
    }

    public function treasurer(){
        return $this->hasOne("User",'id',"treasurer")->field("id,username");
    }

    /**
     * 拒绝统计
     * @author cxr <1481746137@qq.com>
     * @param $keywords
     * @param $page
     * @param $limit
     * @param $valuedate
     * @param string $os
     * @param string $status
     * @param $startdate
     * @param $enddate
     * @param $line             线上线下
     * @param bool $isExport    是否导出
     * @return mixed
     */

    public function getRefuseList($keywords, $page, $limit, $valuedate, $os = '', $status = "", $startdate, $enddate, $line, $isExport = false)
    {


        $where_refuse['a.status'] = array('in', '6,7,8,10,11');
        $map = $where_refuse;

        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate"));
            $vtime = "like '$valuedate%'";
        }
        if ($startdate != '') {
            $vtime = "BETWEEN '$startdate' and '$enddate'";
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }
        #人工或系统
        if ($line == "online") {
            $map['status'] = array('in', '6,7,10,11');
        }
        if ($line == "offline") {
            $map['status'] = array('in', '8');
        }

        $this->where($map);
        $this->alias('a')
             ->with(['claimSeq','checkAid','check2Aid','merchandiser','treasurer'])
             ->order(array('a.status = 9' => 'desc', 'a.status = 3' => 'desc', 'a.status = 4' => 'desc', 'a.status = 5' => 'desc', 'a.status = 11' => 'desc', 'appoint_time' => 'asc', 'fives_claim_date' => 'desc', 'a.id' => 'asc'));

        #根据不同拒绝筛选相应日期
        if ($valuedate || $startdate) {
            $this->whereExp("IF (status = 6, check_time $vtime, '1=1')", "")
                 ->whereExp("IF (status = 7, check_time $vtime, '1=1')", "")
                 ->whereExp("IF (status = 8, time $vtime, '1=1')", "")
                 ->whereExp("IF (status = 10, monepassdate $vtime, '1=1')", "")
                 ->whereExp("IF (status = 11, lendmoneydate $vtime, '1=1')", "");
        }

        #导出
        if ($isExport == true && ($keywords || $valuedate || $startdate)) {
            $list = $this->select();
        } else {
            $listArray = $this->paginate();
            $list = $listArray->items();
            $data['dataCount'] = $listArray->total();
        }

        $list = collection($list)->each(function ($item) use ($isExport) {
            #驳回时间
            $item['refuse_time'] = $this->getRefuseTimeByStatus($item);
            #驳回操作人
//            $item['refuse_person'] = $this->getRefuseByStatus($item);
            $item['refuse_person'] = $this->getPersonByStatus($item);
            #第几次申请
            $count = DB::name("apply")->where('uid', $item['uid'])->where('id', '<=', $item['id'])->count();
            $item['counts'] = $count;
            #人工系统
            $item['pay_type'] = $item['status'];
            $item['times'] = substr($item['time'], 0, 10);
            #排序
//            $mapseq['apply_id'] = $item['id'];
//            $mapseq['auth_admin'] = 3;
//            $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
//            if ($dataseq) {
//                $item['seq'] = $dataseq['seq'];
//            }else{
//                $item['seq'] = '';
//            }
            $item['seq'] = $item['claim_seq']['seq'];
            #导出时
            $isExport && $item['status_export'] = $this->statusInfo($item['status']);
            $isExport && $item['pay_type_export'] = $item['status'] == "8" ? "系统拒绝" : "人工拒绝";

            return $item;
        });

        //print_r($list->toArray());exit;


//        foreach ($list as $key => $value) {
//
//            $list[$key]['refuse_time'] = $this->getRefuseTimeByStatus($value);
//            $list[$key]['refuse_person'] = $this->getRefuseByStatus($value);      //驳回操作人
//
//            //第几次申请
//            $mapuid['uid'] = $value['uid'];
//            $count = DB::name("apply")->where($mapuid)->where('id', '<=', $value['id'])->count();
//            $list[$key]['counts'] = $count;
//
//            //线下或线上放款
//            $where['apply_id'] = $value['order_number'];
//            $list[$key]['pay_type']  =  $value['status'];
//
//           // $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);
//            $list[$key]['appoint_time'] = substr($value['appoint_time'], 0, 10);
//            $list[$key]['times'] = substr($value['time'], 0, 10);
//
//            $mapseq['apply_id'] = $value['id'];
//            $mapseq['auth_admin'] = 3;
//            $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
//            if (!$dataseq) {
//                $list[$key]['seq'] = '';
//            } else {
//                $list[$key]['seq'] = $dataseq['seq'];
//            }
//
//            //导出时
//            $isExport && $list[$key]['status_export']=$this->statusInfo($list[$key]['status']);
//            $isExport && $list[$key]['pay_type_export']= $value['status']=="8"?"系统拒绝":"人工拒绝";
//        }

        $data['list'] = $list;

        $where_refuse = $map;
        #拒绝时间统计
        if ($valuedate || $startdate) {
            $total = $this->all_refuseDate_count('total', $vtime);
            $online = $this->all_refuseDate_count('online', $vtime);
            $offline = $this->all_refuseDate_count('offline', $vtime);
        } else {
            $total = $this->all_refuse_count($where_refuse, 'total');
            $online = $this->all_refuse_count($where_refuse, 'online');
            $offline = $this->all_refuse_count($where_refuse, 'offline');
        }

        $data['money'] = $total['money'];
        $data['number'] = $total['number'];

        $data['onlineMoney'] = $online['money'];
        $data['onlineNumber'] = $online['number'];

        $data['offlineMoney'] = $offline['money'];
        $data['offlineNumber'] = $offline['number'];

        return $data;

    }

    /**
     * 拒绝统计
     * @author cxr <1481746137@qq.com>
     * @param $keywords
     * @param $page
     * @param $limit
     * @param $valuedate
     * @param string $os
     * @param string $status
     * @param $startdate
     * @param $enddate
     * @param $line             普通认证 极速认证 vip认证
     * @param bool $isExport    是否导出
     * @return mixed
     */

    public function getAuthList($keywords, $page, $limit, $valuedate, $os = '', $status = "", $startdate, $enddate, $line, $isExport = false)
    {


        $where_auth['pay_result'] = 'SUCCESS';
        $map = $where_auth;

        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate"));
            $map['create_time'] = ['like', '%' . $valuedate . '%']; // 原 create_time
        }
        if ($startdate != '') {
            $map['create_time'] = array('BETWEEN', [$startdate, $enddate]);
        }
        if ($keywords) {
//            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }
        #普通 极速 vip
        if ($line ) {
            $map['a.auth_type'] = $line;
        }
//        var_dump($map);exit;
        $authModel = new ApplyOrder();;
        $authModel = $authModel
            ->where($map)
            ->field('a.*,b.name,b.period,b.money,b.status')
            ->join("qh_apply b", "b.order_number=a.apply_id", "LEFT")
            ->alias('a')
            ->order('create_time desc,a.auth_type desc');
//            ->with(['claimSeq','checkAid','check2Aid','merchandiser','treasurer'])
//            ->order(array('a.status = 9' => 'desc', 'a.status = 3' => 'desc', 'a.status = 4' => 'desc', 'a.status = 5' => 'desc', 'a.status = 11' => 'desc', 'appoint_time' => 'asc', 'fives_claim_date' => 'desc', 'a.id' => 'asc'));

        #导出
        if ($isExport == true && ($keywords || $valuedate || $startdate)) {
            $list = $authModel->select();
        } else {
            $listArray = $authModel->paginate();
            $list = $listArray->items();


            $data['dataCount'] = $listArray->total();
        }

        $list = collection($list)->each(function ($item) use ($isExport) {
            #驳回时间
//            $item['refuse_time'] = $this->getRefuseTimeByStatus($item);
            #驳回操作人
//            $item['refuse_person'] = $this->getRefuseByStatus($item);
            #第几次申请
//            $count = DB::name("apply")->where('uid', $item['uid'])->where('id', '<=', $item['id'])->count();
//            $item['counts'] = $count;
            #人工系统
//            $item['pay_type'] = $item['status'];
//            $item['times'] = substr($item['time'], 0, 10);

            #导出时
            $isExport && $item['status_export'] = $this->statusInfo($item['status']);
            $isExport && $item['pay_type_export'] = $item['status'] == "8" ? "系统拒绝" : "人工拒绝";

            return $item;
        });


        $data['list'] = $list;

        $where_refuse = $map;


            $total = $this->all_auth_count($where_refuse);
            $online = $this->all_auth_count($where_refuse, 1);
            $offline = $this->all_auth_count($where_refuse, 2);

        $data['money'] = $total['money'];
        $data['number'] = $total['number'];

        $data['fastMoney'] = $online['money'];
        $data['fastNumber'] = $online['number'];

        $data['vipMoney'] = $offline['money'];
        $data['vipNumber'] = $offline['number'];

        return $data;

    }



    public function getDelayList($keywords, $page, $limit, $valuedate, $os = '', $status = "", $startdate, $enddate, $line, $isExport = false)
    {


        //$where_yanqi['a.status'] = ['in','0,1,2,3,4,5,6,7,8,9,10,12,11.13,14'];
//        $where_yanqi['no_order'] = ['like', '%XQ%']; // 总
        $where_yanqi['type'] = 2; // 总

        $where_yanqi['result_pay'] = 'SUCCESS';

        $map = $where_yanqi;

        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate"));
            $map['pay_time'] = ['like', '%' . $valuedate . '%']; // 原 create_time
        }
        if ($startdate != '') {
            $map['pay_time'] = array('BETWEEN', [$startdate, $enddate]); //原 create_time
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }

        //线上线下
        $line == "online" && $map['no_order'] = ['neq', 'XQ'];
        $line == "offline" && $map['no_order'] = ['eq', 'XQ'];


        $this->where($map);

        // 若有分页
        if ($page && $limit && !$isExport && !($keywords || $valuedate || $startdate)) {
            $this->page($page, $limit);
        }
        $this->field("a.id,a.uid,appoint_time,a.time,a.status,a.period,a.money,a.name,delay_aid,a.order_number,no_order,pay_time as create_time,delay_aid,money_order")
            ->alias("a")
            ->join("qh_user_order b", "a.order_number=b.apply_id", "LEFT")
//            ->order(array('a.status = 9' => 'desc', 'a.status = 3' => 'desc', 'a.status = 4' => 'desc', 'a.status = 5' => 'desc', 'a.status = 11' => 'desc', 'appoint_time' => 'asc', 'fives_claim_date' => 'desc', 'id' => 'asc'))
        ;

        if ($isExport == true && ($keywords || $valuedate || $startdate)) {
            $list = $this->select();
        } else {

            $listArray = $this->paginate();
            $list = $listArray->items();
            $data['dataCount'] = $listArray->total();
        }


        foreach ($list as $key => $value) {

            $list[$key]['delay_aid'] = $this->getNameById($value['delay_aid']);      //延期操作人

            //第几次申请
            $mapuid['uid'] = $value['uid'];
            $count = $this->where($mapuid)->where('id', '<=', $value['id'])->count();
            $list[$key]['counts'] = $count;

            //线下或线上放款
            $where['apply_id'] = $value['order_number'];
            $list[$key]['pay_type'] = $value['no_order'];

//            $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);
            $list[$key]['appoint_time'] = substr($value['appoint_time'], 0, 10);
            $list[$key]['times'] = substr($value['time'], 0, 10);

            $mapseq['apply_id'] = $value['id'];
            $mapseq['auth_admin'] = 3;
            $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
            if (!$dataseq) {
                $list[$key]['seq'] = '';
            } else {
                $list[$key]['seq'] = $dataseq['seq'];
            }

            //导出时
            $isExport && $list[$key]['status_export'] = $this->statusInfo($list[$key]['status']);
            $isExport && $list[$key]['pay_type_export'] = $value['no_order'] != "XQ" ? "线上放款" : "线下放款";
        }
        $data['list'] = $list;

//        var_dump(111);exit;
        //总数线上线下待优化
        // $where_hk['hk_time'] =  $date;// 日期
        //$where_hk = $map;
        //$where_hk['status'] = 5;

        $where_yq = $map;
        

        $total = $this->all_yanqi_count($where_yq, 'total');
        $data['money'] = $total['money'];
        $data['number'] = $total['number'];

//        $online = $this->all_yanqi_count($where_yq, 'online');
//        $data['onlineMoney'] = $online['money'];
//        $data['onlineNumber'] = $online['number'];
//

        $offline = $this->all_yanqi_count($where_yq, 'offline');
        $data['offlineMoney'] = $offline['money'];
        $data['offlineNumber'] = $offline['number'];

        $data['onlineMoney'] = $data['money'] - $data['offlineMoney'];
        $data['onlineNumber'] = $data['number'] - $data['offlineNumber'];


        return $data;

    }

    public function getFkList($keywords, $page, $limit, $valuedate, $os = '', $status = "", $startdate, $enddate, $line, $isExport = false)
    {


        $where_fk['a.status'] = array('in', '3,4,5,12');
        $where_fk['result_pay'] = 'SUCCESS';

        $map = $where_fk;

        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate"));
            $map['fk_time'] = ['like', '%' . $valuedate . '%'];
        }
        if ($startdate != '') {
            $map['fk_time'] = array('BETWEEN', [$startdate, $enddate]);
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }


        //线上线下
        if ($line == "online") {
            $map['type'] = ['eq', '0'];
        }
        if ($line == "offline") {
            $map['type'] = ['eq', '1'];
        }


        $this->where($map);

        // 若有分页
        if ($page && $limit && !$isExport && !($keywords || $valuedate || $startdate)) {
            $this->page($page, $limit);
        }
        $this->field("a.*,no_order,type")
            ->alias("a")
            ->join("qh_payment_order b", "a.order_number=b.apply_id")
            ->order(array('a.status = 9' => 'desc', 'a.status = 3' => 'desc', 'a.status = 4' => 'desc', 'a.status = 5' => 'desc', 'a.status = 11' => 'desc', 'appoint_time' => 'asc', 'fives_claim_date' => 'desc', 'id' => 'asc'));

        if ($isExport == true && ($keywords || $valuedate || $startdate)) {
            $list = $this->select();
        } else {
            $listArray = $this->paginate();
            $list = $listArray->items();
            $data['dataCount'] = $listArray->total();
        }

        foreach ($list as $key => $value) {

            //第几次申请
            $mapuid['uid'] = $value['uid'];
            $count = $this->where($mapuid)->where('id', '<=', $value['id'])->count();
            $list[$key]['counts'] = $count;

            //线下或线上放款
            $where['apply_id'] = $value['order_number'];
//            $list[$key]['pay_type'] = $value['no_order'];
            $list[$key]['type'] == 1 ? $value['pay_type'] = null:$value['pay_type'] = 1;

            $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);
            $list[$key]['appoint_time'] = substr($value['appoint_time'], 0, 10);
            $list[$key]['times'] = substr($value['time'], 0, 10);

            $mapseq['apply_id'] = $value['id'];
            $mapseq['auth_admin'] = 3;
            $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
            if (!$dataseq) {
                $list[$key]['seq'] = '';
            } else {
                $list[$key]['seq'] = $dataseq['seq'];
            }

            //导出时
            $isExport && $list[$key]['status_export'] = $this->statusInfo($list[$key]['status']);
            $isExport && $list[$key]['pay_type_export'] = $value['no_order'] ? "线上放款" : "线下放款";
        }
        $data['list'] = $list;


        //总数线上线下待优化
        // $where_hk['hk_time'] =  $date;// 日期
        //$where_hk = $map;
        //$where_hk['status'] = 5;

        $where_fk = $map;

        $total = $this->all_fk_count($where_fk, 'total');
        $data['money'] = $total['money'];
        $data['number'] = $total['number'];

        $online = $this->all_fk_count($where_fk, 'online');
        $data['onlineMoney'] = $online['money'];
        $data['onlineNumber'] = $online['number'];

        $offline = $this->all_fk_count($where_fk, 'offline');
        $data['offlineMoney'] = $offline['money'];
        $data['offlineNumber'] = $offline['number'];


        return $data;

    }


    /**
     * 功能:     统计放款金额
     * @Author   zhanhuiping
     * @email    18702529695@163.com
     * @DateTime 2017-12-18
     * @param    [type]              $where_fk [description]
     * @param    string $where [description]
     * @return   [type]                        [description]
     */
    public function fk_count($where_fk, $what = 'money')
    {
        $count = Db::name('apply')->alias("a")
            ->field('count(a.id) as number, sum(loan_out_money) as money')
            ->where($where_fk)->select();
        if ($what == 'money') {
            $data = $count[0]['money'];
        } else {
            $data = $count[0]['number'];
        }
        return $data;
    }


    /**
     * 功能:     统计用户
     * @Author   zhanhuiping
     * @email    18702529695@163.com
     * @DateTime 2017-12-15
     * @param    [type]              $where [description]
     * @param    string $what [description]
     * @return   [type]                     [description]
     */
    public function new_count($where_user = null, $where_is = '')
    {


        $count = Db::name('user_info')->where($where_user)
            ->where($where_is)
            ->count();
       $where_time_tuiguang['creat_time'] = $where_user['create_time'];
       if(!$where_time_tuiguang['creat_time'] )
       {
         $where_time_tuiguang = 'creat_time is not null';
       }
       $count_tuiguan_count = Db::name('binvite_commission')->where($where_time_tuiguang)->count('id');
        
       $data['count'] = $count;
       $data['count_pingtai'] = $count-$count_tuiguan_count;
       $data['count_tuiguan_count'] = $count_tuiguan_count;


       return $data;

    }


    /**
     * 功能:     延期费用
     * @Author   zhanhuiping
     * @email    18702529695@163.com
     * @DateTime 2017-12-15
     * @param    [type]              $where [description]
     * @param    string $what [description]
     * @return   [type]                     [description]
     */
    public function yanqi_count($where_yanqi = null, $what = 'money')
    {

        $count = Db::name('user_order')->where($where_yanqi)//->whereOr('no_order','like','%Q1%')
            ->field('sum(money_order) as money, count(id) as number')
            ->select();
//        echo $this->getLastSql();exit;

        if ($what == 'money') {
            $data = $count[0]['money'];
        } else {
            $data = $count[0]['number'];
        }
        return $data;

    }

    /**
     * [查询申请表的金额总数或总次数]
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-18T15:31:29+0800
     * @param    string $where [查询条件]
     * @param    string $what [要返回的数据 money:金额 number:次数]
     * @return   [type]                           [description]
     */
    public function status_count($where = null, $what = 'money')
    {
        $count = Db::name('apply')->where($where)->field('sum(money) as money, count(id) as number')->select();

        if ($what == 'money') {
            $data = $count[0]['money'];
        } else {
            $data = $count[0]['number'];
        }
        return $data;
    }

    public function apply_count($where = null, $what = 'money')
    {
        $count = Db::name('apply')
                ->alias('a')
                ->join('qh_user_info b',"a.uid = b.uid")
                ->where($where)->field('sum(money) as money, count(a.id) as number')->select();

        if ($what == 'money') {
            $data = $count[0]['money'];
        } else {
            $data = $count[0]['number'];
        }
        return $data;
    }

    /**
     * [查询申请表的金额总数或总次数]
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-18T15:31:29+0800
     * @param    string $where [查询条件]
     * @param    string $what [要返回的数据 money:金额 number:次数]
     * @return   [type]                           [description]
     */
    public function hk_count($where = null, $what = 'money', $line = null)
    {
        $count = Db::name('user_order')->where($where)->field('sum(money_order) as money, count(id) as number');

//        $count = Db::name('user_order')->alias('a')->join("qh_apply b", "b.order_number=a.apply_id", "LEFT")->field('sum(money_order) as money, count(a.id) as number');


        $count = $count->select();
        if ($what == 'money') {
            $data = $count[0]['money'];
        } else {
            $data = $count[0]['number'];
        }
        return $data;
    }

    public function auth_count($where = null, $what = 'money', $line = null)
    {
        $count = Db::name('apply_order')->where($where)->field('sum(money_order) as money, count(id) as number');
        $count = $count->select();
        if ($what == 'money') {
            $data = $count[0]['money'];
        } else {
            $data = $count[0]['number'];
        }
        return $data;
    }

    public function all_auth_count($where = null, $line = null)
    {
        if($line !== null)
            $where['a.auth_type'] = $line;

        $count = Db::name('apply_order')->alias('a')->where($where)->field('sum(money_order) as money, count(id) as number');
        $count = $count->find();


        return $count;
    }

    /**
     *[查询申请表的金额总数和总次数]
     * @auth cxr <1481746137@qq.com>
     * @param null $where
     * @param string $what
     * @param null $line
     * @return mixed
     */
    public function all_hk_count($where = null, $what = 'money', $line = null)
    {

        if ($line == null) {
            unset($where['pay_type']);
        }
        $line == 'online' && $where['pay_type'] = 'D';
        $line == 'offline' && $where['pay_type'] = 'XX';

        $count = Db::name('user_order')->alias('a')->join("qh_apply b", "b.order_number=a.apply_id", "LEFT")->field('sum(money_order) as money, count(a.id) as number');
        $data = $count->fetchSql(false)->where($where)->find();

        return $data;
    }

    /**
     *[查询放款金额总数和总次数]
     * @auth cxr <1481746137@qq.com>
     * @param null $where
     * @param string $what
     * @param null $line
     * @return mixed
     */
    public function all_fk_count($where = null, $line = null)
    {
        unset($where['ret_code']);

        $count = Db::name('apply')
            ->field("sum(loan_out_money) as money, count(a.id) as number")
            ->alias("a")
            ->join("qh_payment_order b", "a.order_number=b.apply_id", "LEFT");


        if ($line == "online") {
            $where['type'] = ['eq', '0'];
            //  $where['ret_code'] = '0000';
        }
        $line == "offline" && $where['type'] = ['eq', '1'];
        if ($line == "total") unset($where['type']);

        $data = $count->where($where)->where($map)->find();
        return $data;
    }

    /**
     *[查询拒绝金额总数和总次数]
     * @auth cxr <1481746137@qq.com>
     * @param null $where
     * @param string $what
     * @param null $line
     * @return mixed
     */
    public function all_refuse_count($where = null, $line = null)
    {
        $count = Db::name('apply')->field('sum(money) as money, count(id) as number')->alias("a");

        $line == "online" && $where['status'] = array('in', '6,7,10,11');
        $line == "offline" && $where['status'] = array('in', '8');
        $line == "total" && $where['status'] = array('in', '6,7,8,10,11');


        $data = $count->where($where)->find();
        // var_dump($count->getLastSql());exit;
        if ($line == "offline") {
            //  var_dump($count->getLastSql());exit;
        }
        return $data;
    }

    public function all_refuseDate_count($line, $vtime)
    {
        $line == "online" && $type = "and status in(6,7,10,11)";
        $line == "offline" && $type = "and status in(8)";
        $line == "total" && $type = "and status in(6,7,8,10,11)";


        $sql = "SELECT
                sum(money) as money, count(id) as number
            FROM
                qh_apply
            WHERE
            IF (status = 6, check_time $vtime, '1=1')
            and 
            IF (status = 7, check_time $vtime, '1=1')
            and 
            IF (status = 8, time $vtime, '1=1')
            AND
            IF (status = 10, monepassdate $vtime, '1=1')
            AND
            IF (status = 11, lendmoneydate $vtime, '1=1')
            $type ";
        $data = DB::query($sql);
        //echo  $this->getLastSql();exit;


        return $data[0];
    }

    /**
     *[查询延期金额总数和总次数]
     * @auth cxr <1481746137@qq.com>
     * @param null $where
     * @param string $what
     * @param null $line
     * @return mixed
     */
    public function all_yanqi_count($where = null, $line = null)
    {
        unset($where['phone|order_number|name']);
//        $count = Db::name('apply')
//            ->field("sum(money_order) as money, count(a.id) as number")
//            ->alias("a")
//            ->join("qh_user_order b", "a.order_number=b.apply_id", "left");
        $count = Db::name('user_order')
            ->field("sum(money_order) as money, count(id) as number");

//        $map['no_order'] = ['like', '%XQ%'];
//        $map['type'] = '2';

        $line == "online" && $where['no_order'] = ['neq', 'XQ'];
        $line == "offline" && $where['no_order'] = ['eq', 'XQ'];
        if ($line == "total") unset($where['no_order']);

//        if ($line == "total") {
//            var_dump($count->where($where)->where($map)->fetchSql(true)->find());
//            exit;
//        }
        $data = $count->where($where)->where($map)->find();
        return $data;
    }

    /**
     * 订单状态已经完成时，查询订单支付线上线下
     * @author cxr <1481746137@qq.com>
     * @param $pay_type
     * @return string
     */
    public function getPayType($pay_type)
    {
        return $pay_type == "D" ? "线上" : "线下";
    }


    public function getOverdue360List($keywords, $page, $limit, $valuedate, $os = '', $status = "", $startdate, $enddate, $day, $isExport = false)
    {
        ini_set('memory_limit', '1024M');
        ini_set('max_execution_time', '0');


        $where_yuqi['status'] = 4;
//        $where_yuqi['mthreetransfer'] = 0;
//        $where_yuqi['mtwotransfer'] = 1;
        $where_yuqi['transfer'] = 1;

        $map = $where_yuqi;

        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate -1day"));
            $map['appoint_time'] = ['between',[$valuedate,$valuedate]];
        }

        if ($startdate != '') {
            $map['appoint_time'] = array('BETWEEN', [$startdate, $enddate]);
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }
        $this->where($map);

        // 若有分页
        if ($page && $limit && !$isExport && !($keywords || $valuedate || $startdate)) {
            $this->page($page, $limit);
        }

        $day=0;
        $now = date('Y-m-d');
//        $keys = [ 'name','id_card','phone', 'wechat_id','qq','company','address','money', 'fk_time','appoint_time','overdue_count','overdue_money','repay','lxr'];

//        $this->field("appoint_time,merchandiser,transfer,merchandiser2,mongodb_qqtb_id,b.name,b.id_card,b.phone,qq,wechat_id,address,money,fk_time,overdue_money,DATEDIFF('{$now}',appoint_time) as overdue_count")
        $this->field("*,DATEDIFF('{$now}',appoint_time) as overdue_count")
            ->alias("a")
//            ->whereExp("DATEDIFF('{$now}',appoint_time)>={$day}",'1=1')
            ->join('qh_user_info b',"a.uid = b.uid")
            ->order('time desc');
//            ->limit(1,2);

        if ($isExport == true ) {
            $list = $this->select();

        } else {
            $listArray = $this->paginate();
            $list = $listArray->items();
            $data['dataCount'] = $listArray->total();
        }

        $list = modelo2array($list);

        foreach ($list as $key => $value) {

            // 应还金额
            $list[$key]['repay'] = $this->getRepay($list[$key]['status'], $value, $value['overdue_money']);
            $list[$key]['repay1'] = $list[$key]['repay'];

            !empty($value['merchandiser']) && $CSY = $value['merchandiser'];
            !empty($value['merchandiser2']) && $CSY = $value['merchandiser2'];
            !empty($value['mtwo_admin_user_id']) && $CSY = $value['mtwo_admin_user_id'];
            $list[$key]['CSY'] = $this->getNameById($CSY);

            $list[$key]['lxr'] = '';
            if($value['mongodb_qqtb_id']){
                $res = Db::connect("db_mongo")->name('yueguangbaika')->where("_id",$value['mongodb_qqtb_id'])->find();
                $qqtb_data = $res['qqtb_data'];
                $list[$key]['lxr'] = $qqtb_data;
            }
//
//
//            $qqtb_data = json_decode($qqtb_data,true);


//            print_r($value);exit;
//            // 银行数据
//            $var1 = curlPostForm('http://www.atool.org/include/bank.inc.php',['c'=>$value['bank_card_number']]);
//            $var1 = json_decode($var1,true);
//            echo $var1['m'].'<br>';

            // 联系人
//            $lxr = $value['secret_about'];
//            $lxr = json_decode($lxr['four_contacts'],true);
//            $relation = ['sister'=>'妹妹','friend'=>'朋友','colleague'=>'同事','spouse'=>'配偶','father'=>'父亲','brother'=>'兄弟','mother'=>'母亲'];
//            $list[$key]['lxr'] = $lxr;
//
//            $list[$key]['lxr1name'] = $lxr[0]['name'];
//            $list[$key]['lxr1phone'] = ' '.$lxr[0]['phone'];
//            $list[$key]['lxr1relation'] = $relation[ $lxr[0]['relation'] ];
//
//            $list[$key]['lxr2name'] = $lxr[1]['name'];
//            $list[$key]['lxr2phone'] = ' '.$lxr[1]['phone'];
//            $list[$key]['lxr2relation'] = $relation[ $lxr[1]['relation'] ];
//
//            $list[$key]['lxr3name'] = $lxr[2]['name'];
//            $list[$key]['lxr3phone'] = ' '.$lxr[2]['phone'];
//            $list[$key]['lxr3relation'] = $relation[ $lxr[2]['relation'] ];
//
            $list[$key]['id_card'] = ' '.$list[$key]['id_card'].' ';
            $list[$key]['phone'] = ' '.$list[$key]['phone'].' ';
            $list[$key]['qq'] = ' '.$list[$key]['qq'].' ';
            $list[$key]['wechat_id'] = ' '.$list[$key]['wechat_id'].' ';
//            $list[$key]['bank_card_number'] = ' '.$list[$key]['bank_card_number'].' ';
//            $list[$key]['no_agree'] = ' '.$list[$key]['no_agree'].' ';


            //导出时
//            $isExport && $list[$key]['status_export'] = $this->statusInfo($list[$key]['status']);

        }
//                    var_dump(111);exit;
        $data['list'] = $list;

//        var_dump($data);exit;
//        print_r($data);exit;
        return $data;

    }

    public function match_chinese($chars,$encoding='utf8')
    {
        $pattern =($encoding=='utf8')?'/[\x{4e00}-\x{9fa5}a-zA-Z0-9\:]/u':'/[\x80-\xFF]/';
        preg_match_all($pattern,$chars,$result);
        $temp =join('',$result[0]);
        return $temp;
    }




    /**
     *  导出Excel,返回地址
     * @author cxr <1481746137@qq.com>
     * @param $keywords
     * @param $page
     * @param $limit
     * @param $valuedate
     * @param $os
     * @param $status
     * @return string
     */
    public function export($keywords, $page, $limit, $valuedate, $os = '', $status = "", $startdate, $enddate, $line, $type)
    {

        switch ($type) {
            case "back":
                $typeMethod = "getBackList";
                $arrdata[] = ['排序', '申请时间', '姓名', '状态,', '借款', '期限', '第几次申请', "还款方式", '还款日期', '机型'];
                $keys = ['seq', 'time', 'name', 'status_export', 'money', 'period', 'counts', 'pay_type_export', 'hk_time', 'mobile_type'];
                break;
            case "fk":
                $typeMethod = "getFkList";
                $arrdata[] = ['排序', '申请时间', '姓名', '状态,', '借款', '期限', '第几次申请', "放款金额", "放款方式", '放款日期', '机型'];
                $keys = ['seq', 'time', 'name', 'status_export', 'money', 'period', 'counts', 'loan_out_money', 'pay_type_export', 'fk_time', 'mobile_type'];
                break;
            case "overdue":
                $typeMethod = "getOverdueList";
                $arrdata[] = ['排序', '申请时间', '姓名', '手机号', '状态,', '借款', '期限', '第几次申请', "应还金额", '逾期日期', '机型'];
                $keys = ['seq', 'time', 'name', 'phone', 'status_export', 'money', 'period', 'counts', 'repay', 'appoint_time', 'mobile_type'];
                break;
            case "delay":
                $typeMethod = "getDelayList";
                $arrdata[] = ['排序', '申请时间', '姓名', '状态,', '借款', '期限', '第几次申请', "延期费", "延期方式", '延期日期', '机型', '操作人'];
                $keys = ['seq', 'time', 'name', 'status_export', 'money', 'period', 'counts', 'money_order', 'pay_type_export', 'create_time', 'mobile_type', 'delay_aid'];
                break;
            case "refuse":
                $typeMethod = "getRefuseList";
                $arrdata[] = ['排序', '申请时间', '姓名', '状态,', '借款', '第几次申请', '期限', "驳回方式", '驳回日期', '机型', '驳回员工'];
                $keys = ['seq', 'time', 'name', 'status_export', 'money', 'counts', 'period', 'pay_type_export', 'refuse_time', 'mobile_type', 'refuse_person'];
                break;
            case "overdue360":
                $typeMethod = "getOverdue360List";
                $arrdata[] = ['客户姓名', '身份证号','手机号', '微信','qq','单位名称', '现住址','借款金额','借款日期','约定还款日',      '逾期天数',      '罚息违约金',     '应还总额','催收员','通讯录'];
                $keys = [ 'name','id_card','phone', 'wechat_id','qq','company','address','money', 'fk_time','appoint_time','overdue_count','overdue_money','repay','CSY','lxr'];
                break;

        }

        $data = $this->$typeMethod($keywords, $page, $limit, $valuedate, $os = '', $status = "", $startdate, $enddate, $line, true);
        if ($type == 'back' || $type == 'refuse' || $type == 'overdue360')
            $data = $data['list'];
        else
            $data = modelo2array($data['list']);


        $filter = $this->filterVal($data, $keys);

        if($type == 'overdue360'){
            $this->callHandle($filter);
        }

        if (empty($filter))
            return false;
        $arrdata = array_merge($arrdata, $filter);
        $path = $this->create_xls($arrdata, $type);
        return $path;

    }

    /**
     * 通讯录处理成指定导出格式
     * @author cxr <1481746137@qq.com>
     */
    public function callHandle(&$arr){

        foreach ($arr as $k2 => $v2){
            if( $v2['lxr']){
                $call_data = json_decode($v2['lxr'],true);
                $arr[$k2]['lxr'] = '';
//                var_dump($v2['lxr']);exit;
                if(is_string($call_data)){
                    $call_data = json_decode($call_data,true);
                }
                if(is_array($call_data )){
                    foreach ($call_data as $k => $v){
                        $call_data[$k] = join(':',$v);

//                        $call_data[$k] = iconv("GBK", "UTF-8", $call_data[$k]);
                        $call_data[$k] = $this->match_chinese($call_data[$k]);

                        //过滤emoji表情...
                        $call_data[$k] = emoji_unified_to_softbank($call_data[$k]);

                        $call_data[$k] = str_replace(['-','::::'],['',':'],$call_data[$k]);
                    }

                    $v2['lxr'] = '';
                    if(count($call_data)>21)
                        $call_data = array_slice($call_data,0,20);
                    $arr[$k2] = array_merge($v2, $call_data);
//                    $arr[$k2][3]='';
                }else{
//                    $arr[$k2] = $v2;
                }

            }else{
                $v2['lxr'] = '';
//                $newArr[$k2] = $v2;
            }

        }

//        var_dump($arr);exit;
        return $arr;

    }

    /**
     * 按Key过滤排序
     * @author cxr <1481746137@qq.com>
     * @param $arr
     * @param $keys
     * @return mixed
     */
    public function filterVal($arr, $keys)
    {
        foreach ($keys as $k => $v)
            foreach ($arr as $k2 => $v2)
                $new_array[$k2][$v] = $arr[$k2][$v];
        return $new_array;
    }


    /**
     * 创建财务excel
     * @author cxr <1481746137@qq.com>
     * @param $data
     * @param string $filename
     * @return string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function create_xls($data, $filename = 'myloans.xls')
    {
        ini_set('max_execution_time', '0');
        $filename .= date("Ymdhis");
        $filename = str_replace('.xls', '', $filename) . '.xls';
        $phpexcel = new \PHPExcel();

        $phpexcel->getProperties()
            ->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        $phpexcel->getActiveSheet()->fromArray($data);
        $phpexcel->getActiveSheet()->setTitle('Sheet1');
        $phpexcel->setActiveSheetIndex(0);
        $objwriter = \PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
        $dir = dirname(__FILE__);
        $objwriter->save(ROOT_PATH . '/public/' . $filename);
        return '/public/' . $filename;
    }
    /**
     * [getEchartTotal 获取折线图统计]
     * @param  string $minTime [description]
     * @param  string $maxTime [description]
     * @return [type]          [description]
     */
    public function getEchartTotal($minTime = '', $maxTime = '', $type = 0, $totalMinTime = '', $totalMaxTime = '')
    {

        $where = [];//查询条件
        $where1= [];
        //注册
        $fieldDay = "DATE_FORMAT(create_time,'%d') day";
        //营运商
        $fieldReportDay = "DATE_FORMAT(operator_update_time,'%d') day";
        //银行卡
        $fieldBankDay = "DATE_FORMAT(bank_auth_date,'%d') day";
        //身份证
        $fieldIdCardDay = "DATE_FORMAT(idcard_auth_date,'%d') day";
        //基本信息
        $fieldCommonDay = "DATE_FORMAT(baseinfo_auth_date,'%d') day";
        //qq
        $fieldQqDay = "DATE_FORMAT(qqtb_auth_date,'%d') day";
        //周
        if($type ==1 )
        {
            //注册
            $fieldDay = "DATE_FORMAT(create_time,'%w') day";
            //营运商
            $fieldReportDay = "DATE_FORMAT(operator_update_time,'%w') day";
            //银行卡
            $fieldBankDay = "DATE_FORMAT(bank_auth_date,'%w') day";
            //身份证
            $fieldIdCardDay = "DATE_FORMAT(idcard_auth_date,'%w') day";
            //基本信息
            $fieldCommonDay = "DATE_FORMAT(baseinfo_auth_date,'%w') day";
            //qq
            $fieldQqDay = "DATE_FORMAT(qqtb_auth_date,'%w') day";
        //月
        }elseif($type == 2)
        {
            //注册
            $fieldDay = "DATE_FORMAT(create_time,'%m') day";
            //营运商
            $fieldReportDay = "DATE_FORMAT(operator_update_time,'%m') day";
            //银行卡
            $fieldBankDay = "DATE_FORMAT(bank_auth_date,'%m') day";
            //身份证
            $fieldIdCardDay = "DATE_FORMAT(idcard_auth_date,'%m') day";
            //基本信息
            $fieldCommonDay = "DATE_FORMAT(baseinfo_auth_date,'%m') day";
            //qq
            $fieldQqDay = "DATE_FORMAT(qqtb_auth_date,'%m') day";
        }
        
        //注册
        $reg = 'COUNT(a.id) regCount';
        //银行卡
        $bank = "SUM(if(a.bank_card_number,1,0)) bank";
        //报告
        $report = "SUM(if(a.mongo_operator_report,1,0)) report";
        //身份证
        $idCard = "SUM(if(a.id_card_img1 is not null and a.id_card_img2 is not null,1,0)) card_img";
        //基本信息
        $common = "SUM(if(a.company is not null and a.address is not null and a.zhima is not null and a.qq is not null and a.mon_income is not null and a.wechat_id is not null and a.payday is not null and a.zmf is not null and a.negative_img is not null and a.job is not null,1,0)) common";
        //qq
        $qq = "SUM(if(a.directories,1,0)) qq";
        //资料
        $auth = "SUM(if(a.bank_card_number and a.mongo_operator_report and a.id_card_img1 is not null and a.id_card_img2 is not null and a.company is not null and a.address is not null and a.zhima is not null and a.qq is not null and a.mon_income is not null and a.wechat_id is not null and a.payday is not null and a.zmf is not null and a.negative_img is not null and a.job is not null and a.directories,1,0)) auth";
        //注册
        $field = [
            $reg,
            $fieldDay
        ];
        //银行卡
        $fieldBank = [
            $bank,
            $fieldBankDay
        ];
        //运营商报告
        $fieldReport = [
            $report,
            $fieldReportDay
        ];
        //身份证
        $fieldIdCard = [
            $idCard,
            $fieldIdCardDay
        ];
        //基本信息
        $fieldCommon = [
            $common,
            $fieldCommonDay
        ];
        //qq
        $fieldQq = [
            $qq,
            $fieldQqDay
        ];
        //认证
        $fieldAuth = [
            $auth,
            $fieldQqDay
        ];
        $group = 'day';//分组条件
        //注册
        $where['create_time'] = ['between', [$minTime, $maxTime]];
        //运营商
        $whereReport['operator_update_time'] = ['between', [$minTime, $maxTime]];
        //银行卡
        $whereBank['bank_auth_date'] = ['between', [$minTime, $maxTime]];
        //身份证
        $whereIdCard['idcard_auth_date'] = ['between', [$minTime, $maxTime]];
        //基本信息
        $whereCommon['baseinfo_auth_date'] = ['between', [$minTime, $maxTime]];
        //qq
        $whereQq['qqtb_auth_date'] = ['between', [$minTime, $maxTime]];
        if($totalMinTime && $totalMaxTime)
        {
            //注册
            $where1['create_time'] = ['between', [$totalMinTime, $totalMaxTime]];
            //运营商
            $where1Report['operator_update_time'] = ['between', [$totalMinTime, $totalMaxTime]];
            //银行卡
            $where1Bank['bank_auth_date'] = ['between', [$totalMinTime, $totalMaxTime]];
            //身份证
            $where1IdCard['idcard_auth_date'] = ['between', [$totalMinTime, $totalMaxTime]];
            //基本信息
            $where1Common['baseinfo_auth_date'] = ['between', [$totalMinTime, $totalMaxTime]];
            //qq
            $where1Qq['qqtb_auth_date'] = ['between', [$totalMinTime, $totalMaxTime]];
        }
        $appuser = new Appuser;
        $data['totalGdData']['regCount'] = $appuser->alias('a')->field($field)->where($where)->group($group)->select();//注册折线图统计
        $data['totalGdData']['bank'] = $appuser->alias('a')->field($fieldBank)->where($whereBank)->group($group)->select();//银行卡折线图统计
        $data['totalGdData']['report'] = $appuser->alias('a')->field($fieldReport)->where($whereReport)->group($group)->select();//运营商折线图统计
        $data['totalGdData']['card_img'] = $appuser->alias('a')->field($fieldIdCard)->where($whereIdCard)->group($group)->select();//身份证折线图统计
        $data['totalGdData']['common'] = $appuser->alias('a')->field($fieldCommon)->where($whereCommon)->group($group)->select();//银行卡折线图统计
        $data['totalGdData']['qq'] = $appuser->alias('a')->field($fieldQq)->where($whereQq)->group($group)->select();//qq折线图统计
        $data['totalGdData']['auth'] = $appuser->alias('a')->field($fieldAuth)->where($whereQq)->group($group)->select();//资料折线图统计
        //处理折线图数据
        $this->hanlderGdDatas($data['totalGdData']);
        $data['totalData']['regCount'] = $appuser->alias('a')->where($where1)->value([$reg]);//注册统计
        $data['totalData']['bank'] = $appuser->alias('a')->where($where1Bank)->value([$bank]);//银行卡统计
        $data['totalData']['report'] = $appuser->alias('a')->where($where1Report)->value([$report]);//运营商统计
        $data['totalData']['card_img'] = $appuser->alias('a')->where($where1IdCard)->value([$idCard]);//身份证统计
        $data['totalData']['common'] = $appuser->alias('a')->where($where1Common)->value([$common]);//基本信息统计
        $data['totalData']['qq'] = $appuser->alias('a')->where($where1Qq)->value([$qq]);//qq统计
        $data['totalData']['auth'] = $appuser->alias('a')->where($where1Qq)->value([$auth]);//资料统计*/

        $sum = $this->getSum($minTime, $maxTime, $totalMinTime, $totalMaxTime);    //统计app下载 和 激活
        $data = array_merge($sum,$data);

        //查询日志
        return $data;
    }
    /**
     * [hanlderGdDatas 处理折线图数据  代码有点冗余后期要修改一下]
     * @param  array  &$data [description]
     * @return [type]        [description]
     */
    public function hanlderGdDatas( array &$data = [])
    {
        //当注册没时间不给予理会
        if(!$data['regCount'])
        {
            return false;
        }
        //初始索引
        $bank = 0;
        $report = 0;
        $card_img = 0;
        $common = 0;
        $qq = 0;
        $auth = 0;
        //数据
        $bankArr = [];
        $reportArr = [];
        $card_imgArr = [];
        $commonArr = [];
        $qqArr = [];
        $authArr = [];
        foreach($data['regCount'] as $k => $v)
        {   
            //银行卡
            if(isset($data['bank'][$bank]))
            {
                //判断日期是否相同
                if($data['bank'][$bank]['day'] == $v['day'])
                {
                    $bankArr[] = ['day' => $v['day'], 'bank' => $data['bank'][$bank]['bank']];
                    ++$bank;
                }else{
                    $bankArr[] = ['day' => $v['day'], 'bank' => 0];    
                }
            }else{
                $bankArr[] = ['day' => $v['day'], 'bank' => 0];
            }
            //信用报告
            if(isset($data['report'][$report]))
            {
                //判断日期是否相同
                if($data['report'][$report]['day'] == $v['day'])
                {
                    $reportArr[] = ['day' => $v['day'], 'report' => $data['report'][$report]['report']];
                    ++$report;
                }else{
                    $reportArr[] = ['day' => $v['day'], 'report' => 0];    
                }
            }else{
                $reportArr[] = ['day' => $v['day'], 'report' => 0];
            }
            //身份证
            if(isset($data['card_img'][$card_img]))
            {
                //判断日期是否相同
                if($data['card_img'][$card_img]['day'] == $v['day'])
                {
                    $card_imgArr[] = ['day' => $v['day'], 'card_img' => $data['card_img'][$card_img]['card_img']];
                    ++$card_img;
                }else{
                    $card_imgArr[] = ['day' => $v['day'], 'card_img' => 0];    
                }
            }else{
               $card_imgArr[] = ['day' => $v['day'], 'card_img' => 0];
            }
            //基本资料
            if(isset($data['common'][$common]))
            {
                //判断日期是否相同
                if($data['common'][$common]['day'] == $v['day'])
                {
                    $commonArr[] = ['day' => $v['day'], 'common' => $data['common'][$common]['common']];
                    ++$common;
                }else{
                    $commonArr[] = ['day' => $v['day'], 'common' => 0];    
                }
            }else{
                $commonArr[] = ['day' => $v['day'], 'common' => 0];
            }
            //通讯录
            if(isset($data['qq'][$qq]))
            {
                //判断日期是否相同
                if($data['qq'][$qq]['day'] == $v['day'])
                {
                    $qqArr[] = ['day' => $v['day'], 'qq' => $data['qq'][$qq]['qq']];
                    ++$qq;
                }else{
                    $qqArr[] = ['day' => $v['day'], 'qq' => 0];    
                }
            }else{
                $qqArr[] = ['day' => $v['day'], 'qq' => 0];
            }
            //全部认证
            if(isset($data['auth'][$auth]))
            {
                //判断日期是否相同
                if($data['auth'][$auth]['day'] == $v['day'])
                {
                    $authArr[] = ['day' => $v['day'], 'auth' => $data['auth'][$auth]['auth']];
                    ++$auth;
                }else{
                    $authArr[] = ['day' => $v['day'], 'auth' => 0];    
                }
            }else{
                $authArr[] = ['day' => $v['day'], 'auth' => 0];
            }
        }
        $data['bank'] = $bankArr;
        $data['report'] = $reportArr;
        $data['card_img'] = $card_imgArr;
        $data['common'] = $commonArr;
        $data['qq'] = $qqArr;
        $data['auth'] = $authArr;
    }
    /**
     * 下载量  激活量统计
     * @param $minTime
     * @param $maxTime
     * @param string $totalMinTime
     * @param string $totalMaxTime
     * @return mixed
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     * @AUTHER 范俊成
     * @DATE 2018/4/24
     */
    public function getSum($minTime, $maxTime,$totalMinTime = '', $totalMaxTime = '')
    {
        $sql5 = "select count(*) num,DATE_FORMAT(download_time,'%d') day from qh_extend where download_time BETWEEN '$minTime' AND DATE_ADD('$maxTime',INTERVAL 1 DAY)  AND type='ios' group BY day ";        //折线图ios下载
        $sql6 = "select count(*) num,DATE_FORMAT(download_time,'%d') day from qh_extend where download_time BETWEEN '$minTime' AND DATE_ADD('$maxTime',INTERVAL 1 DAY) AND type='android' group BY day ";    //折线图android下载量
        $sql7 = "select count(*) num,DATE_FORMAT(active_time,'%d') day from qh_extend_user where active_time BETWEEN '$minTime' AND DATE_ADD('$maxTime',INTERVAL 1 DAY) AND type='ios' group BY day ";       //折线图ios激活量
        $sql8 = "select count(*) num,DATE_FORMAT(active_time,'%d') day from qh_extend_user where active_time BETWEEN '$minTime' AND DATE_ADD('$maxTime',INTERVAL 1 DAY) AND type='android' group BY day ";   //折线图android激活量

        if(empty($totalMinTime) && empty($totalMaxTime) ){
            $sql1 = "select count(*) from qh_extend where   type='ios' ";           //ios下载量
            $sql2 = "select count(*) from qh_extend where  type='android' ";       //android下载量
            $sql3 = "select count(*) from qh_extend_user where  type='ios' ";        //ios激活量
            $sql4 = "select count(*) from qh_extend_user where  type='android' ";    //android激活量
        }else{
            $sql1 = "select count(*) from qh_extend where download_time BETWEEN '$totalMinTime' AND '$totalMaxTime'   AND type='ios' ";           //ios下载量
            $sql2 = "select count(*) from qh_extend where download_time BETWEEN '$totalMinTime' AND '$totalMaxTime'   AND type='android' ";       //android下载量
            $sql3 = "select count(*) from qh_extend_user where active_time BETWEEN '$totalMinTime' AND '$totalMaxTime'   AND type='ios' ";        //ios激活量
            $sql4 = "select count(*) from qh_extend_user where active_time BETWEEN '$totalMinTime' AND '$totalMaxTime'   AND type='android' ";
        }


        $data['ios_download_sum'] = $this->query($sql1)[0]['count(*)'];
        $data['android_download_sum'] = $this->query($sql2)[0]['count(*)'];
        $data['ios_active_sum'] = $this->query($sql3)[0]['count(*)'];
        $data['android_active_sum'] = $this->query($sql4)[0]['count(*)'];


        $data['ios_download_zx_sum'] = $this->query($sql5);
        $data['android_download_zx_sum'] = $this->query($sql6);
        $data['ios_active_zx_sum'] = $this->query($sql7);
        $data['android_active_zx_sum'] = $this->query($sql8);
        return  $data;
//        var_dump($data);exit;
    }





    /**
     * [getDateHandlerData 获取日期处理数据]
     * @param  string &$minTime [description]
     * @param  string &$maxTime [description]
     * @return [type]           [description]
     */
    public function getDateHandlerData(&$minTime = '', &$maxTime = '', $data = [])
    {

        $min = strtotime($minTime);//开始时间
        $max = strtotime($maxTime);//结束时间
        $status = true;//循环条件
        do{
            $time = $min;//挑选时间
            $dateData['date'][] = date('Y-m-d',$min);
            $min = strtotime('+1 day', $min);
            if($min > $max)
            {
                $status = false;
            }
        }while($status);

        return $dateData;
    }

}